package com;

/**
 * Created with IntelliJ IDEA.
 * Description:合并二叉树
 * User: YJ
 * Date: 2024-4-27
 * Time: 14:57
 */
public class mergeTreesTest {

    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode s1 = new TreeNode(3);
        TreeNode s2 = new TreeNode(2);
        TreeNode s3 = new TreeNode(5);
        t1.left = s1;
        t1.right = s2;
        s1.left = s3;
        TreeNode t2 = new TreeNode(2);
        TreeNode s4 = new TreeNode(1);
        TreeNode s5 = new TreeNode(3);
        TreeNode s6 = new TreeNode(4);
        TreeNode s7 = new TreeNode(7);
        t2.left = s4;
        t2.right = s5;
        s4.right = s6;
        s5.right = s7;
        TreeNode treeNode = mergeTrees(t1, t2);
        treeOrderTest treeOrderTest = new treeOrderTest();
        treeOrderTest.preOrder(treeNode);
//        treeOrderTest.inOrder(treeNode);
//        treeOrderTest.postOrder(treeNode);
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 已知两颗二叉树，将它们合并成一颗二叉树。
     * 合并规则是：都存在的结点，就将结点值加起来，否则空的位置就由另一个树的结点来代替。
     *
     * @param t1 TreeNode类
     * @param t2 TreeNode类
     * @return TreeNode类
     */
    public static TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        if (t1 == null) return t2;
        if (t2 == null) return t1;
        TreeNode head = new TreeNode(t1.val + t2.val);
        head.left = mergeTrees(t1.left,t2.left);
        head.right = mergeTrees(t1.right,t2.right);
        return head;
    }
}
